package com.datastructure.list;

public class SingleLinkedList implements MyList{
    StudentNode head;
    SingleLinkedList() {
        head = new StudentNode("",0);
    }

    @Override
    public int get(String name) {
        return 0;
    }

    //新增节点在尾节点后
    public void add(StudentNode student) {
        StudentNode temp = head;
        //next == null 就是尾节点
        while (temp.next != null) {
            temp = temp.next;
        }
        temp.next = student;
    }

    @Override
    public void update(StudentNode studentNode) {
        StudentNode temp = head.next;
        while (temp != null) {
            if (temp.name.equals(studentNode.name)) {
                break;
            }
            temp = temp.next;
        }
        if (temp != null) {
            System.out.println("学生 " + studentNode.name
                    + " 的分数从 " + temp.score + " 更新为 " + studentNode.score);
            temp.score = studentNode.score;
        } else {
            System.out.println("学生 " + studentNode.name + " 不存在");
        }
    }

    @Override
    public void del(String name) {
        StudentNode temp = head;
        while (temp.next != null) {
            if (temp.next.name.equals(name)) {
                break;
            }
            temp = temp.next;
        }
        if (temp.next != null) {
            StudentNode delNode = temp.next;
            temp.next = temp.next.next;
            delNode.next = null;
            System.out.println(name + "已被删除");
        }else {
            System.out.println(name + "不在链表中");
        }
    }

    @Override
    public void show() {
        System.out.println("当前链表为：");
        StudentNode temp = head.next;//从第一个数据节点开始展示
        if (temp == null) {
            System.out.println("空链表");
            return;
        }
        while (temp != null) {
            System.out.println(temp);
            temp = temp.next;
        }
    }

    //新增节点按照 score 插入
    @Override
    public void addByScore(StudentNode studentNode) {
        StudentNode temp = head;
        while (temp.next != null) {
            //当前节点是最后一个节点 或 目标节点的分数大于后一个节点
            if(temp.next.score < studentNode.score) {
                break;
            }
            temp = temp.next;
        }
        //节点插入，先将目标节点的next指向temp.next
        //再将 temp.next 指向目标节点
        studentNode.next = temp.next;
        temp.next = studentNode;
    }
}

class StudentNode {
    public String name;
    public int score;
    public StudentNode next;
    public StudentNode pre;
    public StudentNode(String name,int score) {
        this.name = name;
        this.score = score;
        next = null;
        pre = null;
    }

    @Override
    public String toString() {
        return "name: " + this.name + ", score: " + this.score;
    }
}